package com.wu.verifysquenceofbst;

import java.io.Serializable;

/**
 * 二叉树的后序遍历序列
 *
 * @author lynn
 * @date 2020/8/2 - 20:30
 */
public class Solution {
    public static boolean VerifySquenceOfBST(int[] sequence) {
        if (sequence.length == 0 || sequence == null) {
            return false;
        }
        return verify(sequence, 0, sequence.length - 1);
    }

    private static boolean verify(int[] sequence, int start, int end) {
        if (start >= end) {
            return true;
        }
        int root = sequence[end];
        int i;
        for (i = start; i < end; i++) {
            if (sequence[i] > root) {
                break;
            }
        }
        for (int j = i; j < end; j++) {
            if (sequence[j] < root) {
                return false;
            }
        }
        if (start == i) {
            return verify(sequence, start, end - 1);
        }
        return verify(sequence, start, i - 1) && verify(sequence, i, end - 1);
    }

    public static void main(String[] args) {
        int[] num = {5, 7, 6, 9, 11, 10, 8};
        boolean b = VerifySquenceOfBST(num);
        System.out.println(b);
    }
}
